import axios from 'axios'
import router from '@/router';
import { getToken,getIpAddress } from '@/utils/auth';
// create an axios instance
const service = axios.create({
    baseURL: "/api/", // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000 // request timeout
})

service.interceptors.request.use(
    config => {
        // do something before request is sent

        if (getToken()) {
            // let each request carry token
            // ['X-Token'] is a custom headers key
            // please modify it according to the actual situation
            config.headers['satoken'] = getToken()
        }
        if(getIpAddress()){
            config.headers['ipAddress'] = getIpAddress()
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)
// response interceptor
service.interceptors.response.use(
    /**
     * If you want to get http information such as headers or status
     * Please return  response => response
     */

    /**
     * Determine the request status by custom code
     * Here is just an example
     * You can also judge the status by HTTP Status Code
     */
    response => {
        const res = response.data
        // console.log(this);
        if (res.code === 401) {
            console.log(res.code);
            localStorage.removeItem("token")
            localStorage.removeItem("router")
            localStorage.removeItem("userId")
            router.push("login")
            return;
        } else {
            return response
        }

    }
)


export default service